import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:syria_sports/core/app_export.dart';

import '../../data/remote/database_helper.dart';
import '../../presentation/sync_screen/sync_screen.dart';

enum InternetState { connected, disconnected , loading }

class InternetCubit extends Cubit<InternetState> {
  final Connectivity _connectivity;
  static InternetCubit get(context) => BlocProvider.of(context);

  InternetCubit(this._connectivity) : super(InternetState.connected) {
    _monitorConnection();
  }

  void _monitorConnection() {
    if(kIsWeb){
      emit(InternetState.connected);
      return;
    }
    print('connection is loading');
    emit(InternetState.loading);
    _connectivity.onConnectivityChanged.listen((result) {
    print('connection is $result');
      if (result.isEmpty || result.first == ConnectivityResult.none) {
        ScaffoldMessenger.of(NavigatorService.navigatorKey.currentContext!).showSnackBar(
          SnackBar(
            backgroundColor: theme.primaryColor,
            content: Text('انت في وضع عدم الاتصال',style: theme.textTheme.titleMedium,),
          ),
        );
        emit(InternetState.disconnected);
      } else {
        _syncData(NavigatorService.navigatorKey.currentContext!);
        emit(InternetState.connected);
      }
    });
  }

  void _syncData(BuildContext context)async{
    if(Platform.isWindows)return;
    var res = await DatabaseHelper.getPendingOperations();
    if(res.isNotEmpty){
      showDialog(
          context: NavigatorService.navigatorKey.currentContext!,
          builder: (BuildContext context) {
            return AlertDialog(
              title: const Text('يوجد بينات غير مزامنة'),
              content: const Text('هل تريد مزامنة البيانات الآن؟'),
              actions: [
                TextButton(onPressed: (){
                  Navigator.of(context, rootNavigator: true).pushReplacement(
                    MaterialPageRoute(
                      builder: (context) => const SyncScreen(),
                    ),
                  );
                }, child: Text('نعم',style: theme.textTheme.labelLarge,)),
                TextButton(onPressed: (){
                  Navigator.of(context).pop();
                }, child: Text('لا شكراً',style: theme.textTheme.labelLarge,)),
              ],
            );
          });
    }

  }
}
